package com.lframework.starter.web.core.aop;

import com.lframework.starter.web.core.annotations.sort.Sort;
import com.lframework.starter.web.core.annotations.sort.Sorts;
import com.lframework.starter.web.core.utils.JoinQuerySortUtil;
import com.lframework.starter.web.core.vo.SortPageVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Join查询排序AOP
 */
@Aspect
public class JoinQuerySortsAspector {

    @Pointcut("@annotation(com.lframework.starter.web.core.annotations.sort.Sorts) || @annotation(com.lframework.starter.web.core.annotations.sort.Sort)")
    public void sortPointCut() {

    }

    @Around(value = "sortPointCut()")
    public Object sortAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        List<Sort> sortList = new ArrayList<>();
        Sort sort = methodSignature.getMethod().getAnnotation(Sort.class);
        if (Objects.nonNull(sort)) {
            sortList.add(sort);
        }
        Sorts sorts = methodSignature.getMethod().getAnnotation(Sorts.class);
        if (Objects.nonNull(sorts)) {
            sortList.addAll(Arrays.asList(sorts.value()));
        }
        if (!sortList.isEmpty()) {
            List<SortPageVo> sortPageVos = Arrays.stream(joinPoint.getArgs())
                    .filter(arg -> arg instanceof SortPageVo)
                    .map(arg -> (SortPageVo) arg)
                    .collect(Collectors.toList());
            JoinQuerySortUtil.setQuerySort(sortList, sortPageVos);
        }
        try {
            return joinPoint.proceed();
        } finally {
            JoinQuerySortUtil.clear();
        }
    }

}
